package com.san.metadata.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.san.base.controller.BaseController;
import com.san.base.domain.DictDO;
import com.san.base.service.DictService;
import com.san.common.annotation.Log;
import com.san.common.utils.Constant;
import com.san.common.utils.PageUtils;
import com.san.common.utils.Query;
import com.san.common.utils.R;
import com.san.metadata.domain.BusinessDataDO;
import com.san.metadata.domain.ColumnDTO;
import com.san.metadata.domain.TableDTO;
import com.san.metadata.service.BusinessDataService;
import com.san.metadata.service.ManageMetadataService;
import com.san.metadata.vo.BusinessDataVO;

/**
 * 业务元数据
 * @author SuperSR
 * @date 2019年3月6日 上午10:24:39
 *
 */
@RequestMapping("/md/business")
@Controller
public class BusinessDataController extends BaseController{

	private String PREFIX = "metadata/business";
	private static final Logger logger = LoggerFactory.getLogger(BusinessDataController.class);
	@Autowired
	private DictService dictService;
	@Autowired
	private BusinessDataService businessDataService;
	@Autowired
	private ManageMetadataService manageMetadataService;
	
	
	@GetMapping("")
	@RequiresPermissions("md:business:view")
	String source(Model model) {
		return PREFIX + "/view";
	}
	
	/**
	 * 查询业务元数据列表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("md:business:view")
	public PageUtils list(@RequestParam Map<String, Object> params){
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			Query query = new Query(params);
			List<BusinessDataDO> list = businessDataService.list(query);
			int total = businessDataService.count(query);
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("获取业务元数据列表失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 进入新增页面
	 * @return
	 */
	@GetMapping("/add")
	@RequiresPermissions("md:business:add")
	String add() {
		return PREFIX + "/add";
	}
	
	/**
	 * 保存新增业务元数据
	 * @param businessDataVO
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("md:business:add")
	@Log("新增业务元数据")
	public R save(BusinessDataVO businessDataVO) {
		try{
				businessDataVO.setOperator(getUserName());
				int result = businessDataService.save(businessDataVO);
				if(result == -1){
					return R.error("该业务元数据已经存在");
				}else if(result == -2){
					return R.error("新增业务元数据失败");
				}else if (result == -3){
					return R.error("存在非法字符");
				}else if (result == -4){
					return R.error("sql语法不规范");
				}else if (result > 0) {
					return R.ok();
				}
			}catch (Exception e) {
				logger.error("新增业务元数据失败",e);
			}
		return R.error();
	}
	
	/**
	 * 编辑业务元数据
	 * @param businessDataVO
	 * @return
	 */
	@ResponseBody
	@PostMapping("/doEdit")
	@RequiresPermissions("md:business:edit")
	@Log("编辑业务元数据")
	public R doEdit(BusinessDataVO businessDataVO) {
		try{
				int result = businessDataService.doEdit(businessDataVO);
				if(result == -1){
					return R.error("该业务元数据已经存在");
				}else if(result == -2){
					return R.error("新增业务元数据失败");
				}else if (result == -3){
					return R.error("存在非法字符");
				}else if (result == -4){
					return R.error("sql语法不规范");
				}else if (result > 0) {
					return R.ok();
				}
			}catch (Exception e) {
				logger.error("编辑业务元数据失败",e);
			}
		return R.error();
	}
	
	
	/**
	 * 进入编辑业务元数据界面
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/edit/{id}")
	@RequiresPermissions("md:business:edit")
	String edit(@PathVariable("id") Long id, Model model) {
		BusinessDataDO business = businessDataService.getById(id);
		model.addAttribute("business", business);
		return PREFIX + "/edit";
	}
	
	/**
	 * 进入详细字段列表页
	 * @param tableId
	 * @param model
	 * @return
	 */
	@GetMapping("/toDetField/{tableId}")
	@RequiresPermissions("md:business:add")
	String toDetField(@PathVariable("tableId") Long tableId, Model model) {
		model.addAttribute("tableId", tableId);
		return PREFIX + "/detfieldview";
	}
	
	/**
	 * 查询明细字段
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/detField/{tableId}")
	@RequiresPermissions("md:business:view")
	public PageUtils detField(@PathVariable("tableId") Long tableId){
		List<ColumnDTO> list = null;
		PageUtils pageUtils = null;
		try{
			// 查询列表数据
			list = manageMetadataService.listManageColumns(tableId);
			int total = 0;
			if(list != null){
				total = list.size();
			}
			pageUtils = new PageUtils(list, total);
		}catch(Exception e){
			logger.error("查询字段失败",e);
		}
		return pageUtils;
	}
	
	/**
	 * 删除业务元数据
	 * @param id
	 * @return
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("md:business:remove")
	@Log("删除业务元数据")
	public R remove(Long id) {
		try{
			businessDataService.remove(id);
			return R.ok();
		}catch(Exception e){
			logger.error("删除业务元数据失败",e);
		}
		return R.error();
	}
	
	/**
	 * 批量删除评分等级
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("md:business:batchRemove")
	@Log("批量删除业务元数据")
	public R remove(@RequestParam("ids[]") Long[] ids) {
		try{
			int state = businessDataService.batchRemove(ids);
			if(state == -1){
				return R.error("所选评分等级中存在有明细项，无法删除");
			}else if (state > 0) {
				return R.ok();
			}
		}catch(Exception e){
			logger.error("批量删除评分等级失败",e);
		}
		return R.error();
	}
	
	/**
	 * 根据value查询数据字典
	 * @param value
	 * @return
	 */
	@ResponseBody
	@GetMapping("/byValue")
	public List<DictDO> getByValue(String value) {
		// 查询列表数据
		List<DictDO> list = dictService.getByValue(value);
		return null == list ? new ArrayList<DictDO>() : list;
	}
	
	/**
	 * 查询业务类型
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/busiType")
	public List<DictDO> getBusiType() {
		// 查询列表数据
		List<DictDO> list = dictService.getBusiType();
		return null == list ? new ArrayList<DictDO>() : list;
	}
	
	/**
	 * 查询业务类型子项
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/busiTypeNode")
	public List<DictDO> getBusiTypeNode(Long parentId) {
		// 查询列表数据
		List<DictDO> list = dictService.getBusiTypeNode(parentId);
		return null == list ? new ArrayList<DictDO>() : list;
	}	

	/**
	 * 查询表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getTable")
	public List<TableDTO> getTable(int dataType) {
		// 查询列表数据
		List<TableDTO> list = null;
		try {
			if(dataType == Constant.BUSINESS_DATA_TYPE_LEGAL_PERSON){
				int[] data = {Constant.MANAGE_DATA_TYPE_LEGAL_PERSON , Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON , Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON };
				list = manageMetadataService.listTable2(data);
			}else if(dataType == Constant.BUSINESS_DATA_TYPE_NATURAL_PERSON){
				int[] data = {Constant.MANAGE_DATA_TYPE_NATURAL_PERSON , Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_OR_NATURAL_PERSON , Constant.MANAGE_DATA_TYPE_LEGAL_PERSON_AND_NATURAL_PERSON , Constant.MANAGE_DATA_TYPE_NATURAL_PERSON_OR_NATURAL_PERSON };
				list = manageMetadataService.listTable2(data);
			}
		} catch (Exception e) {
			logger.error("查询表失败",e);
		}
		return null == list ? new ArrayList<TableDTO>() : list;
	}
	
	/**
	 * 查询表
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getTable1")
	public List<TableDTO> getTable1(int dataType) {
		// 查询列表数据
		List<TableDTO> list = null;
		try {
			list = manageMetadataService.listTable1(dataType);
		} catch (Exception e) {
			logger.error("查询表失败",e);
		}
		return null == list ? new ArrayList<TableDTO>() : list;
	}
	
	/**
	 * 查询字段
	 * @param tableId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getField")
	public List<ColumnDTO> getField(Long tableId) {
		// 查询列表数据
		List<ColumnDTO> list = null;
		try {
			list = manageMetadataService.listManageColumns(tableId);
		} catch (Exception e) {
			logger.error("查询字段失败",e);
		}
		return null == list ? new ArrayList<ColumnDTO>() : list;
	}
	
	/**
	 * 查询多个字段
	 * @param tableId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getByDetFieldId")
	public String getByDetFieldId(String id) {
		// 查询列表数据
		String ids = "";
		try {
			ids = businessDataService.getByDetFieldId(id);
		} catch (Exception e) {
			logger.error("查询多个字段失败",e);
		}
		return ids;
	}
	
	/**
	 * 控制业务元数据状态
	 * @param id
	 * @param delFlag
	 * @return
	 */
	@PostMapping(value = "/changeStatus")
	@RequiresPermissions("md:business:changeStatus")
	@ResponseBody
	public R changeStatus(Long id,int delFlag ) {
		String label = "";
		if (delFlag == 1) {
			label = "禁用";
		} else {
			label = "启用";
		}
		BusinessDataVO businessDataVO = new BusinessDataVO();
		businessDataVO.setBusiId(id);
		businessDataVO.setDelFlag(delFlag);
		try {
			businessDataService.changeStatus(businessDataVO);
			return R.ok("元数据" + label + "成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok("元数据" + label + "失败");
	}
	
	/**
	 * 根据数据类型查询业务元数据
	 * @param modelType
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getByDataType")
	public List<BusinessDataDO> getByDataType(String modelType) {
		// 查询列表数据
		List<BusinessDataDO> list = businessDataService.getByDataType(modelType);
		return null == list ? new ArrayList<BusinessDataDO>() : list;
	}
	
	/**
	 * 根据tableId获取表的数据类型
	 * @param tableId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/getTableType")
	public Long getTableType(Long tableId) {
		// 查询列表数据
		Long tableType;
		try {
			tableType = manageMetadataService.getById(tableId).getDataType();
			if(tableType != null){
				return tableType;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}








